<template lang="pug">
Select(
  v-bind="select"
  :onSelect="(option) => onSelect(option)",
  v-model="model"
  @keyup.enter.prevent="filterMethod"
  ref="selectRef"
  @visible-change="onVisibleChange"
)
</template>

<script setup lang="ts">
import { type SelectProps, Select } from "@scmt/common-components";
import { useApi, type ApiBasedOption } from "@scmt/core-api";
import { useRequest } from "@scmt/common-hooks";
import { PortfolioProjectEndpoint } from "@scmt/api-lis-portfolio-project";
//添加事件
const emit = defineEmits(["select"]);

const selectRef = ref<null | InstanceType<typeof Select>>(null);
const $api = useApi();
const model = ref("");

const { request, data } = useRequest(
  {
    westernMedicine: async (key: string) => {
      return $api.lis.portfolioProject.listAsOptions(key);
    },
  },
  {
    westernMedicine: [] as Array<ApiBasedOption>,
  }
);
const filterMethod = () => {
  if (selectRef.value) {
    request("westernMedicine", selectRef.value?.inputValue);
  }
};
const select = computed<SelectProps>(() => {
  return {
    placeholder: "检查项目",
    filterable: true,
    options: data.westernMedicine ?? [],
    modelValue: model.value,
    tableColumns: [
      {
        label: "项目编码",
        prop: "code",
        width: 100,
      },
      {
        label: "项目名称",
        prop: "name",
        width: 100,
      },
      {
        label: "计价单位",
        prop: "price",
        width: 100,
      },
    ],
  };
});
const onSelect = (option: ApiBasedOption<PortfolioProjectEndpoint>) => {
  if (option && option._raw) {
    let item = Object.assign(
      {},
      {
        id: option.value, // 项目id
        name: option.label, // 项目名称
        specimenTypeId: option._raw.specimenTypeId, // 标本类型id
      }
    );
    emit("select", item);
  }
};
const onVisibleChange = (visible: boolean) => {
  if (!visible) {
    Object.assign(data, {
      westernMedicine: [],
    });
  }
};
</script>

<style lang="less" scoped></style>
